<template>
  <div class="bg-white flex flex-col">
    <div class="w-[350px] m-auto flex flex-col md:w-[1440px] md:m-auto">
      <!-- Banner区域 -->
      <div class="relative w-full h-[600px] bg-gradient-to-r from-gray-800 to-gray-900 overflow-hidden cursor-pointer" @click="goToBannerDetail">
        <!-- 背景图片 -->
        <div class="absolute inset-0">
          <img
            :src="currentBannerImage"
            class="w-full h-full object-cover opacity-70"
            alt="Banner Background"
          />
        </div>
        
        <!-- 内容覆盖层 -->
        <!-- <div class="absolute inset-0 bg-black bg-opacity-40">
        </div> -->
        
        <!-- 新闻描述区域 - 悬浮在底部 -->
        <div class="absolute bottom-20 left-0 right-0 z-10">
          <div class="px-12 pb-1">
            <div class="text-white">
              <!-- HOT标签 -->
              <div class="flex items-center mb-4">
                <img v-if="currentNews.newsType === 'hot'" class="w-[160px] h-[50px]" src="@/assets/images/hot.png" alt="HOT" />
                <img v-if="currentNews.newsType === 'latest'" class="w-[160px] h-[50px]" src="@/assets/images/latest.png" alt="LATEST" />
                <img v-if="currentNews.newsType === 'popular'" class="w-[160px] h-[50px]" src="@/assets/images/popular.png" alt="POPULAR" />
              </div>
              
              <!-- 新闻标题 -->
              <h1 class="text-4xl md:text-5xl font-bold leading-tight mb-4">
                {{ currentNews.title }}
              </h1>
            </div>
          </div>
          <a-divider :size="2" />
        </div>
        
        <!-- 轮播指示器 -->
        <div class="absolute bottom-8 left-1/2 transform -translate-x-1/2 flex space-x-2 z-20">
          <button
            v-for="(item, index) in bannerNews"
            :key="index"
            @click="currentBannerIndex = index"
            :class="[
              'w-3 h-3 rounded-full transition-all duration-300',
              currentBannerIndex === index ? 'bg-blue-500' : 'bg-white bg-opacity-50'
            ]"
          ></button>
        </div>
      </div>
      
      <!-- 自定义tabs内容 -->
      <div class="bg-white py-8">
        <!-- Tab导航栏 -->
        <div class="flex justify-center items-center">
          <div class="flex items-center space-x-32">
            <!-- 左侧心电图装饰 -->
            <div class="flex items-center">
              <img class="w-[175px] h-[30px]" src="@/assets/images/arrow-left.png" />
            </div>
            
            <!-- Tab按钮组 -->
            <div class="flex space-x-16">
              <button 
                @click="handleTabClick('latest')"
                :class="[
                  'px-6 py-3 text-[27px] font-medium transition-all duration-300',
                  activeTab === 'latest' 
                    ? 'text-primary' 
                    : 'text-primary opacity-30 hover:text-primary'
                ]"
              >
                Latest News
              </button>
              
              <button 
                @click="handleTabClick('popular')"
                :class="[
                  'px-6 py-3 text-[27px] font-medium transition-all duration-300',
                  activeTab === 'popular' 
                    ? 'text-primary' 
                    : 'text-primary opacity-30 hover:text-primary'
                ]"
              >
                Popular News
              </button>
              
              <button 
                @click="handleTabClick('hot')"
                :class="[
                  'px-6 py-3 text-[27px] font-medium transition-all duration-300 relative',
                  activeTab === 'hot' 
                    ? 'text-primary' 
                    : 'text-primary opacity-30 hover:text-primary'
                ]"
              >
                Hot News
              </button>
            </div>
            
            <!-- 右侧心电图装饰 -->
            <div class="flex items-center">
              <img class="w-[175px] h-[30px]" src="@/assets/images/arrow-right.png" />
            </div>
          </div>
        </div>
        
        <!-- Tab内容区域 -->
        <div class="px-4">
          <div v-if="activeTab === 'latest'" class="flex flex-col items-center">
            <div v-for="(item, index) in latestNews" :key="index" class="w-full max-w-[1200px]">
              <SidedLayout 
                :title="item.title" 
                :desc="item.summary" 
                :bgImg="item.coverImage" 
                :date="item.createAt"
                :id="item.id"
              />
            </div>
          </div>
          
          <div v-if="activeTab === 'popular'" class="flex flex-col items-center"> <!-- 添加 flex 和 items-center 使内容居中 -->
            <div v-for="(item, index) in popularNews" :key="index" class="w-full max-w-[1200px]"> <!-- 添加最大宽度和宽度100% -->
              <SidedLayout :title="item.title" :desc="item.summary" :bgImg="item.coverImage" :date="item.createAt"/>
            </div>
          </div>
          
          <div v-if="activeTab === 'hot'" class="flex flex-col items-center"> <!-- 添加 flex 和 items-center 使内容居中 -->
            <div v-for="(item, index) in hotNews" :key="index" class="w-full max-w-[1200px]"> <!-- 添加最大宽度和宽度100% -->
              <SidedLayout :title="item.title" :desc="item.summary" :bgImg="item.coverImage" :date="item.createAt"/>
            </div>
          </div>
          <!-- 替换原来的分页组件为左右翻页按钮 -->
          <div class="m-auto w-[45%] flex justify-between items-center pb-[30px]">
            <!-- 左翻页按钮 -->
            <button
            @click="handlePrevPage"
            :disabled="isPrevDisabled"
            :class="[
            'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
            { 'opacity-50': isPrevDisabled }
            ]">
            <img class="w-[50px] h-[50px]" src="@/assets/images/previous.png" />
            </button>
            
            <!-- 右翻页按钮 -->
            <button
              @click="handleNextPage"
              :disabled="isNextDisabled"
              :class="[
              'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
              { 'opacity-50': isNextDisabled }
              ]">
              <img class="w-[50px] h-[50px]" src="@/assets/images/next.png" />
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- <FooterBg /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import SidedLayout from '@/components/SidedLayout.vue'
import { contentListApi } from '@/api/content'
import { useRouter } from 'vue-router'
const router = useRouter()

// Banner轮播数据
const bannerNews = ref([] as any[])

const currentBannerIndex = ref(0)

// 添加tab状态管理
const activeTab = ref('latest')

// 计算当前显示的新闻和图片
const currentNews = computed(() => bannerNews.value[currentBannerIndex.value] || {})
const currentBannerImage = computed(() => {
  const news = bannerNews.value[currentBannerIndex.value]
  return news ? news.coverImage : ''
})

// 自动轮播
let autoPlayTimer: NodeJS.Timeout

// 最新研究成果
const latestNews = ref([] as any[])

// 最新研究成果当前页码
const latestNewsCurrentPage = ref(1)

// 最新研究成果总页数
const latestNewsTotalPages = ref(0)

// 高影响力文章推荐
const popularNews = ref([] as any[])

// 高影响力文章推荐当前页码
const popularNewsCurrentPage = ref(1)

// 高影响力文章推荐总页数
const popularNewsTotalPages = ref(0)

// 行业突破新闻
const hotNews = ref([] as any[])

// 行业突破新闻当前页码
const hotNewsCurrentPage = ref(1)

// 行业突破新闻总页数
const hotNewsTotalPages = ref(0)

// 计算是否禁用上一页按钮
const isPrevDisabled = computed(() => {
  return (activeTab.value === 'latest' && latestNewsCurrentPage.value === 1) 
    || (activeTab.value === 'popular' && popularNewsCurrentPage.value === 1) 
    || (activeTab.value === 'hot' && hotNewsCurrentPage.value === 1)
})

const isNextDisabled = computed(() => {
  return (activeTab.value === 'latest' && latestNewsCurrentPage.value === latestNewsTotalPages.value) 
    || (activeTab.value === 'popular' && popularNewsCurrentPage.value === popularNewsTotalPages.value) 
    || (activeTab.value === 'hot' && hotNewsCurrentPage.value === hotNewsTotalPages.value)
})

const startAutoPlay = () => {
  // 只有当bannerNews有数据时才开始轮播
  if (bannerNews.value.length === 0) return
  
  autoPlayTimer = setInterval(() => {
    currentBannerIndex.value = (currentBannerIndex.value + 1) % bannerNews.value.length
  }, 5000) // 5秒切换一次
}

onMounted(() => {
  getBannerNews().then(() => {
    // 确保有数据后再开始轮播
    if (bannerNews.value.length > 0) {
      startAutoPlay()
    }
  })
  getLatestNews()
})

const stopAutoPlay = () => {
  if (autoPlayTimer) {
    clearInterval(autoPlayTimer)
  }
}

const getBannerNews = async () => {
  // 清空现有的bannerNews数据
  bannerNews.value = []
  
  // 直接定义参数对象，不需要额外嵌套
  let latest = {
    recommend: true,
    category: 'news',
    newsType: 'latest',
    status: 'publish',
    limit: 2,
    page: 1
  }

  let popular = {
    recommend: true,
    category: 'news',
    newsType: 'popular',
    status: 'publish',
    limit: 2,
    page: 1
  }

  let hot = {
    recommend: true,
    category: 'news',
    newsType: 'hot',
    status: 'publish',
    limit: 2,
    page: 1
  }

  try {
    // 分别调用三次API获取不同类型的新闻
    const latestRes: any = await contentListApi(latest)
    if (latestRes.code === 0 && latestRes.data && latestRes.data.list) {
      // 将latest类型的新闻添加到bannerNews
      const latestNews = latestRes.data.list.map((item: any) => ({
        ...item,
        newsType: 'latest' // 添加newsType字段
      }))
      bannerNews.value = [...bannerNews.value, ...latestNews]
    }
  } catch (error) {
    console.error('获取latest新闻数据失败:', error)
  }

  try {
    const popularRes: any = await contentListApi(popular)
    if (popularRes.code === 0 && popularRes.data && popularRes.data.list) {
      // 将popular类型的新闻添加到bannerNews
      const popularNews = popularRes.data.list.map((item: any) => ({
        ...item,
        newsType: 'popular' // 添加newsType字段
      }))
      bannerNews.value = [...bannerNews.value, ...popularNews]
    }
  } catch (error) {
    console.error('获取popular新闻数据失败:', error)
  }

  try {
    const hotRes: any = await contentListApi(hot)
    if (hotRes.code === 0 && hotRes.data && hotRes.data.list) {
      // 将hot类型的新闻添加到bannerNews
      const hotNews = hotRes.data.list.map((item: any) => ({
        ...item,
        newsType: 'hot' // 添加newsType字段
      }))
      bannerNews.value = [...bannerNews.value, ...hotNews]
    }
  } catch (error) {
    console.error('获取hot新闻数据失败:', error)
  }
}

const getLatestNews = async (page: number = 1) => {
  try {
    const params = {
      category: 'news',
      newsType: 'latest',
      status: 'publish',
      limit: 3,
      page: page
    }
    const res: any = await contentListApi(params)
    if (res.code === 0 && res.data && res.data.list) {
      latestNewsTotalPages.value = Math.ceil(res.data.total/params.limit)
      latestNews.value = res.data.list
    }
  } catch (error) {
    console.error('获取最新新闻数据失败:', error)
  }
}

const getPopularNews = async (page: number = 1) => {
  try {
    const params = {
      category: 'news',
      newsType: 'popular',
      status: 'publish',
      limit: 3,
      page: page
    }
    const res: any = await contentListApi(params)
    if (res.code === 0 && res.data && res.data.list) {
      popularNewsTotalPages.value =Math.ceil(res.data.total/params.limit)
      popularNews.value = res.data.list
    }
  } catch (error) {
    console.error('获取高影响力文章推荐数据失败:', error)
  }
}

const getHotNews = async (page: number = 1) => {
  try {
    const params = {
      category: 'news',
      newsType: 'hot',
      status: 'publish',
      limit: 3,
      page: page
    }
    const res: any = await contentListApi(params)
    if (res.code === 0 && res.data && res.data.list) {
      hotNewsTotalPages.value = Math.ceil(res.data.total/params.limit)
      hotNews.value = res.data.list
    }
  } catch (error) {
    console.error('获取行业突破新闻数据失败:', error)
  }
}

const handleTabClick = (tab: string) => {
  activeTab.value = tab
  if(tab === 'latest') {
    getLatestNews()
  }
  if (tab === 'popular') {
    getPopularNews()
  }
  if (tab === 'hot') {
    getHotNews()
  }
}

const handleNextPage = () => {
  if(activeTab.value === 'latest') {
    getLatestNews(++ latestNewsCurrentPage.value)
  }
  if(activeTab.value === 'popular') {
    getPopularNews(++ popularNewsCurrentPage.value)
  }
  if(activeTab.value === 'hot') {
    getHotNews(++ hotNewsCurrentPage.value)
  }
}

const handlePrevPage = () => {
  if(activeTab.value === 'latest') {
    // 确保页码不小于1
    if(latestNewsCurrentPage.value > 1) {
      getLatestNews(-- latestNewsCurrentPage.value)
    }
  }
  if(activeTab.value === 'popular') {
    // 确保页码不小于1
    if(popularNewsCurrentPage.value > 1) {
      getPopularNews(-- popularNewsCurrentPage.value)
    }
  }
  if(activeTab.value === 'hot') {
    // 确保页码不小于1
    if(hotNewsCurrentPage.value > 1) {
      getHotNews(-- hotNewsCurrentPage.value)
    }
  }
}

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  stopAutoPlay()
})
// 修改 Banner 点击跳转方法
const goToBannerDetail = () => {
  if (currentNews.value && currentNews.value.id) {
    router.push({
      path: '/news_detail', // 修改路径，去掉 /layout
      query: {
        id: currentNews.value.id
      }
    })
  }
}
</script>

<style scoped>
/* 可以添加一些自定义样式 */
.banner-transition {
  transition: all 0.5s ease-in-out;
}
</style>
